package com.xtpt.disaster.common.SQLServer;

import com.xtpt.disaster.bean.DbnodeInfo;
import org.apache.juli.OneLineFormatter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jack_xin
 * @ClassName FullCommand
 * @Desc 生成SQLServer能在cmd执行的数据库备份语句拼接
 * @Desc 命令示例：sqlcmd  -SWNODE106\DISASTER_RECOVER  -Usa  -P123456 -Q "BACKUP DATABASE SQLTestDB TO DISK='C:\Program Files\Microsoft SQL Server\MSSQL15.DISASTER_RECOVER\MSSQL\Backup\test.bak'"
 * @date 2021年12月06日 15:45
 * @Version TODO
 */
public class SQLServerCommandGenerator {
    public static String BackupCommand(DbnodeInfo dbnodeInfo, String backupFilePath)  {
        //获取数据库相关信息
        String dbName = dbnodeInfo.getNodeDbName();
        String dbUsername = dbnodeInfo.getNodeDbUsername();
        String dbPasswd = dbnodeInfo.getNodeDbPassword();
        String dbBackupRootPath = dbnodeInfo.getNodeDbBackupPath();
        //生成数据库本地备份的文件名称

        String instanceName = dbnodeInfo.getNodeDbServiceName();

        String transactSQLCommand = "\"BACKUP DATABASE %1$s TO DISK= \'%2$s\'\"";
        String cmd = String.format(transactSQLCommand, dbName, backupFilePath);
        String fullcommand = "sqlcmd -S" + instanceName + " -U" + dbUsername + " -P" + dbPasswd + " -Q " + cmd;
        return fullcommand;
    }

    public static List<String> RecoverCommand(DbnodeInfo dbnodeInfo, String recoverFilePath)  {
        //获取数据库相关信息
        List<String> recoverCommands = new ArrayList<>();
        String dbName = dbnodeInfo.getNodeDbName();
        String dbUsername = dbnodeInfo.getNodeDbUsername();
        String dbPasswd = dbnodeInfo.getNodeDbPassword();
        String dbBackupRootPath = dbnodeInfo.getNodeDbBackupPath();
        //生成数据库本地备份的文件名称

        String instanceName = dbnodeInfo.getNodeDbServiceName();

        //sqlcmd
        String sqlcommand = "sqlcmd -S" + instanceName + " -U" + dbUsername + " -P" + dbPasswd + " -Q ";

        String OffLineAndRollBackCommand = "\"ALTER DATABASE %s SET OFFLINE WITH ROLLBACK IMMEDIATE\"";
        String transactSQLRecoverCommand = "\"RESTORE DATABASE %1$s FROM DISK= \'%2$s\' WITH REPLACE\"";
        String DbOnLineCommand = "\"ALTER DATABASE %s SET ONLINE\"";

        String OffLineCommand = String.format(OffLineAndRollBackCommand, dbName);
        String transactSQLRecoverCmd = String.format(transactSQLRecoverCommand, dbName, recoverFilePath);
        String OnLineCommand = String.format(DbOnLineCommand, dbName);

        recoverCommands.add(sqlcommand + OffLineCommand);
        recoverCommands.add(sqlcommand + transactSQLRecoverCmd);
        recoverCommands.add(sqlcommand + OnLineCommand);
        return recoverCommands;
    }
}
